<?php

namespace App\Providers;

use App\Models\Account;
use App\Observers\AccountObserver;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
        $this->registerObserve();
        $this->registerValidator();

        //        DB::listen(function (QueryExecuted $query) {
        //            $sqlWithPlaceholders = str_replace(['%', '?'], ['%%', '%s'], $query->sql);
        //            $bindings = $query->connection->prepareBindings($query->bindings);
        //            $pdo = $query->connection->getPdo();
        //            $realSql = vsprintf($sqlWithPlaceholders, array_map([$pdo, 'quote'], $bindings));
        //            $duration = $this->formatDuration($query->time / 1000);
        //            Log::debug(sprintf('[%s] %s | %s: %s', $duration, $realSql, request()->method(), request()->getRequestUri()));
        //        });
    }

    //    private function formatDuration($seconds)
    //    {
    //        if ($seconds < 0.001) {
    //            return round($seconds * 1000000).'μs';
    //        } elseif ($seconds < 1) {
    //            return round($seconds * 1000, 2).'ms';
    //        }
    //        return round($seconds, 2).'s';
    //    }

    private function registerValidator()
    {
        Validator::extend('loginPassword', 'App\Rules\Auth\Validator@loginPassword');
        Validator::extend('payPassword', 'App\Rules\Auth\Validator@payPassword');
        Validator::extend('password', 'App\Rules\Auth\Validator@password');
        Validator::extend('payPasswordFormat', 'App\Rules\Auth\Validator@payPasswordFormat');
        Validator::extend('usernameExists', 'App\Rules\Auth\Validator@usernameExists');
        Validator::extend('checknum', 'App\Rules\Auth\Validator@checknum');
        //        Validator::extend('emailOrMobileExists', 'App\Rules\Auth\Validator@emailOrMobileExists');
        Validator::extend('wallet_address', 'App\Rules\Address\Validator@walletAddress');
        Validator::extend('emailCode', 'App\Services\Email@checkCode');
        Validator::extend('smsCode', 'App\Services\Sms@checkCode');
    }

    private function registerObserve()
    {
        Account::observe(AccountObserver::class);
    }
}
